/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteoCal.boundary;

import it.polimi.meteoCal.entity.Users;
import java.security.Principal;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Michele
 */
@Stateless
public class UsersFacade extends AbstractFacade<Users> {

    @PersistenceContext
    EntityManager em;
    @Inject
    Principal principal;
    @EJB
    RequestFacade requestFacade;
    @EJB
    UpdatesFacade updateFacade;
    @EJB
    BadWeatherNotificationFacade bwnFacade;
    @EJB
    SuggestionFacade suggestionFacade;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    /**
     * Method to persist the new user registered
     *
     * @param user: the new registered user
     */
    @Override
    public void create(Users user) {
        em.persist(user);
    }

    public void edit(List<Users> usersList) {
        for (Users u : usersList) {
            this.edit(u);
        }
    }

    @Override
    public List<Users> findAll() {
        List<Users> usersList = em.createNamedQuery(Users.findAll, Users.class)
                .setParameter("username", getLoggedUser().getUsername())
                .getResultList();
        return usersList;
    }

    /**
     * Constructor method
     */
    public UsersFacade() {
        super(Users.class);
    }

    public Boolean isUsernameUnique(String username) {
        List<Users> usernameList = em.createNamedQuery(Users.findByUsername, Users.class)
                .setParameter("username", username)
                .getResultList();
        return usernameList.isEmpty();
    }

    public Boolean isEmailUnique(String email) {
        List<Users> usernameList = em.createNamedQuery(Users.findByEmail, Users.class)
                .setParameter("email", email)
                .getResultList();
        return usernameList.isEmpty();
    }

    public Users getLoggedUser() {
        return em.find(Users.class, principal.getName());
    }

    public int countNotifications(Users user) {
        int requestsNum = requestFacade.count(user);
        int bwnNum = bwnFacade.count(user);
        int suggestionNum = suggestionFacade.count(user);
        int updatesNum = updateFacade.count(user);
        return requestsNum + bwnNum + suggestionNum + updatesNum;
    }

}
